import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import _ from 'lodash';
import { Modal, Upload, Button, Icon, message, Progress } from 'antd';
import { getCert, uploadCert, clusterUploadCert } from '@api/cert';
import moment from 'moment';
import cn from 'classnames';
import './index.less';

const prefixCls = 'About';
const modulesMap = {
  statics: '综合分析',
  'asset-detection': '资产探测',
  'asset-manage': '资产管理',
  'asset-config': '资产设置',
  '1day': '1 DAY 检测',
  'task-manage': '任务管理',
  'log-manage': '日志管理',
  notice: '通知',
  'personal|account': '账号设置',
  'personal|message': '消息设置',
  'personal|message|sms': '短信',
  'system|user': '用户管理',
  'system|remote-assist': '远程协助',
  'system|network': '网络配置',
  'system|update': '系统更新',
  about: '产品信息',
  'system|strategy-manage': '策略管理',
  detection: '下发任务',
  'ip-location': '资产地图',
  'Passive-asset-detection': '被动资产探测',
  'Internet-asset-query': '公网资产查询',
  distribute: '集群部署',
  api: 'API接口'
};
class ProductInformation extends Component {
  constructor(props) {
    super(props);
    this.state = {
      deviceId: '',
      isTrial: false,
      expiryTime: 0,
      userNum: 0,
      targetNum: 0,
      modules: [],
      visible: false,
      fileList: [],
      confirmLoading: false,
      proScanCount: null,
      proScanUsedCount: 0,
      isScanCount: false
    };
  }

  componentDidMount() {
    this.getCert();
  }

  getCert = (update = false) => {
    setTimeout(
      () => {
        getCert()
          .then(res => {
            const deviceId = _.get(res.data.data, 'result.device_ids[0]', '');
            const isTrial = _.get(res.data.data, 'result.is_trial', false);
            const expiryTime = _.get(res.data.data, 'result.expiry_time', '') * 1000;
            const userNum = _.get(res.data.data, 'result.max_user_number', 0);
            const targetNum = _.get(res.data.data, 'result.max_target_number', 0);
            const modules = _.get(res.data.data, 'result.modules', []);
            const maxTargetNumber = _.get(res.data.data, 'result.max_target_number', 0);
            const assetAmount = _.get(res.data.data, 'result.assetAmount', 0);
            const zoomeyeOrgAssetAmount = _.get(res.data.data, 'result.zoomeyeOrgAssetAmount', 0);
            const proScanCount = _.get(res.data.data, 'result.zoomeyepro_scan_count', 600000);
            const proScanUsedCount = _.get(res.data.data, 'result.zoomeyepro_scan_used_count', 0);
            const isScanCount =
              _.get(res.data.data, 'result.zoomeyepro_scan_count') !== -1 &&
              _.get(res.data.data, 'result.zoomeyepro_scan_count') !== null &&
              _.get(res.data.data, 'result.zoomeyepro_scan_used_count') !== null;
            if (update) {
              message.success('证书验证通过');
            }
            this.setState({
              deviceId,
              isTrial,
              expiryTime,
              userNum,
              targetNum,
              modules,
              maxTargetNumber,
              assetAmount,
              zoomeyeOrgAssetAmount,
              proScanCount,
              proScanUsedCount,
              isScanCount
            });
          })
          .catch(res => {
            const message = _.get(res, 'message', '获取证书信息失败');
            message.error(message);
          });
      },
      update ? 2000 : 0
    );
  };

  importCertificate = e => {
    e.preventDefault();
    this.setState({ visible: true });
  };

  onCancel = () => {
    this.setState({ visible: false });
  };

  beforeUpload = file => {
    this.setState({ fileList: [file] });
    return false;
  };

  uploadCert = () => {
    const { fileList } = this.state;
    const { userId, modules } = this.props;
    let getMessageSuccess = true;

    const createFormData = () => {
      const body = new FormData();

      if (!fileList[0]) {
        return message.warning('请上传证书文件');
      }
      body.append('file', fileList[0]);
      body.append('userId', userId);

      return body;
    };
    const onUploadSuccess = () => {
      message.success('上传证书成功');
    };
    const onUploadFail = error => {
      const message = _.get(error, 'message', '获取证书失败');
      getMessageSuccess = false;
      message.error(message);
    };
    const onUploadFinish = () => {
      const newCertObject = this.getCert(getMessageSuccess);
      this.setState(newCertObject);

      this.setState({
        visible: false,
        confirmLoading: false
      });
    };

    this.setState({ confirmLoading: true });

    // 集群版本和单机版本调用不同的上传证书接口
    const isCluster = _.includes(modules, 'distribute');
    const uploadCertApi = isCluster ? clusterUploadCert : uploadCert;

    uploadCertApi(createFormData())
      .then(onUploadSuccess)
      .catch(onUploadFail)
      .finally(onUploadFinish);
  };

  renderStatus = () => {
    const { isTrial } = this.state;
    return (
      <div>
        {isTrial ? (
          <div className={`${prefixCls}-item-detail-tag-try`}>试用版</div>
        ) : (
          <div className={`${prefixCls}-item-detail-tag-formal`}>正式版</div>
        )}
      </div>
    );
  };

  renderModules = modules => {
    let filteredModules = _.uniq(modules.filter(item => modulesMap[item]));
    return (
      <div className={`${prefixCls}-modules`}>
        {filteredModules.length
          ? filteredModules.map((item, index, all) => {
              if (index + 1 === all.length) {
                return modulesMap[item] && <span key={index}>{modulesMap[item]}</span>;
              }
              return (
                modulesMap[item] && (
                  <span key={index}>
                    {modulesMap[item]}
                    <span className={`${prefixCls}-modules-line`} />
                  </span>
                )
              );
            })
          : '-'}
      </div>
    );
  };

  renderAuthedModules = () => {
    const { modules } = this.state;
    return this.renderModules(modules);
  };

  renderUnAuthedModules = () => {
    const { modules } = this.state;
    const totalModules = Object.keys(modulesMap);
    const unAuthedModules = _.difference(totalModules, modules);
    return this.renderModules(unAuthedModules);
  };

  onRemove = () => {
    this.setState({ fileList: [] });
  };

  render() {
    const { role, cert, deviceId } = this.props;
    const {
      visible,
      fileList,
      expiryTime,
      userNum,
      confirmLoading,
      assetAmount,
      maxTargetNumber,
      zoomeyeOrgAssetAmount,
      proScanUsedCount,
      modules,
      proScanCount,
      isTrial,
      isScanCount
    } = this.state;
    const oemId = _.get(cert, 'oem_id');
    const customer = _.get(cert, 'customer');
    const formatCustomer = customer === '-' || !customer ? '' : customer;
    const queryMaxTargetNumber = modules.includes('Internet-asset-query') ? maxTargetNumber : 0;
    return (
      <div className={prefixCls}>
        <div className={`${prefixCls}-page-title`}>产品信息</div>
        <div className={`${prefixCls}-item`}>
          <div className={`${prefixCls}-item-title`}>公司名称</div>
          <div className={`${prefixCls}-item-detail`}>
            {oemId ? _.get(cert, 'oem_company_name_cn', '') : '北京知道创宇信息技术股份有限公司'}
          </div>
        </div>
        <div className={`${prefixCls}-item`}>
          <div className={`${prefixCls}-item-title`}>产品名称</div>
          <div className={`${prefixCls}-item-detail`}>
            {oemId ? _.get(cert, 'oem_product_name_cn', '') : 'ZoomEye Pro'}
          </div>
        </div>
        <div className={`${prefixCls}-item`}>
          <div className={`${prefixCls}-item-title`}>版本状态</div>
          {this.renderStatus()}
        </div>
        <div className={`${prefixCls}-item`}>
          <div className={`${prefixCls}-item-title`}>设备</div>
          <div className={`${prefixCls}-item-detail`}>{deviceId}</div>
        </div>
        {formatCustomer && (
          <div className={`${prefixCls}-item`}>
            <div className={`${prefixCls}-item-title`}>授权单位</div>
            <div className={`${prefixCls}-item-detail`}>{formatCustomer}</div>
          </div>
        )}
        <div className={`${prefixCls}-item`}>
          <div className={`${prefixCls}-item-title`}>授权期限</div>
          <div className={`${prefixCls}-item-detail`}>
            {moment(expiryTime).format('YYYY-MM-DD HH:mm')}
          </div>
        </div>
        <div className={`${prefixCls}-item`}>
          <div className={`${prefixCls}-item-title`}>用户数</div>
          <div className={`${prefixCls}-item-detail`}>{userNum}</div>
        </div>
        <div className={`${prefixCls}-item`}>
          <div className={`${prefixCls}-item-title`}>可管理资产数</div>
          <div className={cn(`${prefixCls}-item-detail`, 'progress-item')}>
            <Progress
              className={'progress'}
              percent={(assetAmount / maxTargetNumber) * 100}
              showInfo={false}
            />
            <div>{`${assetAmount} / ${maxTargetNumber}`}</div>
          </div>
        </div>
        {modules.includes('Internet-asset-query') && (
          <>
            <div className={`${prefixCls}-item`}>
              <div className={`${prefixCls}-item-title`}>公网查询条数</div>
              <div className={cn(`${prefixCls}-item-detail`, 'progress-item')}>
                <Progress
                  className={'progress'}
                  percent={(zoomeyeOrgAssetAmount / queryMaxTargetNumber) * 100}
                  showInfo={false}
                />
                <div>{`${zoomeyeOrgAssetAmount} / ${queryMaxTargetNumber}`}</div>
              </div>
            </div>
          </>
        )}
        {isTrial ? (
          <>
            <div className={`${prefixCls}-item`}>
              <div className={`${prefixCls}-item-title`}>资产扫描次数</div>
              <div className={cn(`${prefixCls}-item-detail`, 'progress-item')}>
                {!isScanCount ? (
                  '不限制'
                ) : (
                  <>
                    <Progress
                      className={'progress'}
                      percent={(proScanUsedCount / proScanCount) * 100}
                      showInfo={false}
                    />
                    <div>{`${proScanUsedCount} / ${proScanCount}`}</div>
                  </>
                )}
              </div>
            </div>
          </>
        ) : (
          <div className={`${prefixCls}-item`}>
            <div className={`${prefixCls}-item-title`}>资产扫描次数</div>
            <div className={cn(`${prefixCls}-item-detail`, 'progress-item')}>不限制</div>
          </div>
        )}
        <div className={`${prefixCls}-item`}>
          <div className={`${prefixCls}-item-title`}>授权模块</div>
          <div className={`${prefixCls}-item-detail`} style={{ width: '80%' }}>
            {this.renderAuthedModules()}
          </div>
        </div>
        <div className={`${prefixCls}-item`}>
          <div className={`${prefixCls}-item-title`}>未授权模块</div>
          <div className={`${prefixCls}-item-detail`} style={{ width: '80%' }}>
            {this.renderUnAuthedModules()}
          </div>
        </div>
        {role === '系统管理员' && (
          <div className={`${prefixCls}-item`}>
            <div className={`${prefixCls}-item-title`}>导入证书</div>
            <div className={`${prefixCls}-item-detail`}>
              <a className="be-color" href="/" onClick={e => this.importCertificate(e)}>
                导入
              </a>
            </div>
          </div>
        )}
        <Modal
          maskClosable={false}
          className={cn('import-modal', 'no-header-bottom-lines', 'bottom-center', 'padding-24')}
          visible={visible}
          title="导入证书"
          onOk={this.uploadCert}
          onCancel={this.onCancel}
          confirmLoading={confirmLoading}
        >
          <div className={`${prefixCls}-modal-content`}>
            <div className="modal-item" style={{ marginBottom: 16 }}>
              <div className="modal-item-title">设备标识</div>
              <div>{deviceId}</div>
            </div>
            <div className="modal-item">
              <div className="modal-item-title">证书</div>
              <div style={{ width: '80%' }}>
                <Upload
                  beforeUpload={this.beforeUpload}
                  accept=".lic"
                  fileList={fileList}
                  onRemove={this.onRemove}
                >
                  <Button style={{ width: 200 }}>
                    <Icon type="upload" /> 点击上传“.lic”格式文件
                  </Button>
                </Upload>
              </div>
            </div>
          </div>
        </Modal>
        <div className={`${prefixCls}-item`}>
          <div className={`${prefixCls}-item-title`}>版权声明</div>
          <div className={`${prefixCls}-item-detail`}>
            版权所有&copy;许可证颁发者
            {oemId ? _.get(cert, 'oem_company_name_cn', '') : '北京知道创宇信息技术股份有限公司'}
            ，保留所有权利（公司徽标、产品徽标、公司名称、产品名称）
            <br />
            在中国或其他国家（地区）的商标或注册商标，其商标是其各自所有者财产。
            <br />
            产品所用到的第三方组件所有权为第三方所有。
          </div>
        </div>
      </div>
    );
  }
}

const mapStateToProps = state => {
  return {
    role: _.get(state, 'auth.user.role', ''),
    userId: _.get(state, 'auth.user.user_id', false),
    cert: _.get(state, 'auth.cert', {}),
    deviceId: _.get(state, 'auth.deviceId', '')
  };
};

ProductInformation.propTypes = {
  cert: PropTypes.object,
  deviceId: PropTypes.string,
  userId: PropTypes.string,
  role: PropTypes.object,
  modules: PropTypes.array
};
export default connect(mapStateToProps)(ProductInformation);
